package com.youi.shop.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.po.TableFill;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;

import java.util.ArrayList;
import java.util.List;

//import com.baomidou.mybatisplus.core.config.GlobalConfig;

/**
 * @version 1.0
 * @Author: xxf
 * @CreateDate: 2020/11/7 14:22
 */
public class CodeGenerator {

    //设置你要生成的表名
//    private static final String SET_INCLUDE = "tb_cart";


    private static final String PACKAGE_NAME = "com.youi.shop";
    private static final String OUT_PATH = "/src/main/java";
    private static final String PROJECT_PATH = "D:\\IdeaProjects\\china-good-shop\\shop";
    private static final String AUTHOR  = "xxf";
    private static final String ENTITY  = "pojo.entity";
    private static final String DRIVER  = "com.mysql.cj.jdbc.Driver";
    private static final String URL  = "jdbc:mysql://localhost:3306/shop1.0?useSSL=false&serverTimezone=UTC&autoReconnect=true&useUnicode=true&characterEncoding=UTF-8";
    private static final String USER_NAME  = "root";
    private static final String PASSWORD  = "123456";



    public static void test1() {
        //需要构建一个代码自动生成器的对象
        AutoGenerator autoGenerator = new AutoGenerator();
        //配置策略

        //1.全局配置
        //注意不要导错包
        GlobalConfig gc = new GlobalConfig();
        String projectPath = System.getProperty("user.dir");
        gc.setOutputDir(projectPath+"/src/main/java");
        gc.setAuthor("DJ同学");
        gc.setOpen(false);//生成完文件，是否打开资源管理器
        gc.setFileOverride(true);//是否覆盖原来生成的文件
        gc.setServiceName("%sService");
        gc.setIdType(IdType.ASSIGN_ID);
        gc.setDateType(DateType.ONLY_DATE);
        autoGenerator.setGlobalConfig(gc);
        //2.设置数据源
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl("jdbc:mysql://localhost:3306/mybatis_plus?useUnicode=true&useSSL=false&characterEncoding=utf8");
        dsc.setDriverName("com.mysql.jdbc.Driver");
        dsc.setUsername("root");
        dsc.setPassword("123456");
        autoGenerator.setDataSource(dsc);
        //3.包的配置
        PackageConfig pc = new PackageConfig();
        pc.setModuleName(null);
//        pc.setParent("com.jmu");
//        pc.setEntity("pojo");
//        pc.setMapper("mapper");
//        pc.setService("service");
//        pc.setController("controller");
        autoGenerator.setPackageInfo(pc);

        //4.策略
        // 策略配置
        StrategyConfig strategy = new StrategyConfig();
        strategy.setInclude("user");//设置要映射的表
        strategy.setNaming(NamingStrategy.underline_to_camel);//包命名 驼峰命名
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);//
        strategy.setEntityLombokModel(true);
        strategy.setLogicDeleteFieldName("deleted");//逻辑删除
        //自动填充
        TableFill createTime = new TableFill("create_time", FieldFill.INSERT_UPDATE);
        TableFill updateTime = new TableFill("update_time", FieldFill.UPDATE);
        ArrayList<TableFill> tableFills = new ArrayList<>();
        tableFills.add(createTime);
        tableFills.add(updateTime);
        strategy.setTableFillList(tableFills);
        //乐观锁
        strategy.setVersionFieldName("version");
        autoGenerator.setStrategy(strategy);

        autoGenerator.execute();//执行
    }

    public static void main(String[] args) {
       new CodeGenerator().test2();
    }

    public void test2() {
        // 1、创建代码生成器
        AutoGenerator mpg = new AutoGenerator();

        // 2、全局配置
        GlobalConfig gc = new GlobalConfig();
//        String projectPath = System.getProperty("user.dir");
        //建议直接换成绝对路径  不然有时候会出错
        //****
        gc.setOutputDir( PROJECT_PATH + OUT_PATH);
        //****
        gc.setAuthor(AUTHOR);
        gc.setOpen(false); //生成后是否打开资源管理器
        gc.setFileOverride(true); //重新生成时文件是否覆盖
        gc.setServiceName("%sService");	//去掉Service接口的首字母I
        //如果数据库中的主键是str ID_WORKER_STR int ID_WORKER
        //****
        gc.setIdType(IdType.ASSIGN_ID); //主键策略
        gc.setDateType(DateType.ONLY_DATE);//定义生成的实体类中日期类型
        gc.setSwagger2(true);//开启Swagger2模式

        mpg.setGlobalConfig(gc);

        // 3、数据源配置
        //****
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl(URL);
        dsc.setDriverName(DRIVER);
        dsc.setUsername(USER_NAME);
        dsc.setPassword(PASSWORD);
        dsc.setDbType(DbType.MYSQL);
        mpg.setDataSource(dsc);

        // 4、包配置
        PackageConfig pc = new PackageConfig();
        //com.edu.eduservice
        //****
        pc.setParent(PACKAGE_NAME);
        pc.setEntity(ENTITY);
        //****

        mpg.setPackageInfo(pc);

        // 自定义配置
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
                // to do nothing
            }
        };

        // 如果模板引擎是 freemarker
        String templatePath = "/templates/mapper.xml.ftl";
        // 如果模板引擎是 velocity
//         String templatePath = "/templates/mapper.xml.vm";

        // 自定义输出配置
        List<FileOutConfig> focList = new ArrayList<>();
        // 自定义配置会被优先输出
        focList.add(new FileOutConfig(templatePath) {
            @Override
            public String outputFile(com.baomidou.mybatisplus.generator.config.po.TableInfo tableInfo) {
                // 自定义输出文件名 ， 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化！！
                return PROJECT_PATH + "/src/main/resources/mapper/"
                        + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
            }


        });

        cfg.setFileOutConfigList(focList);
        mpg.setCfg(cfg);

        // 配置模板
        TemplateConfig templateConfig = new TemplateConfig();

        templateConfig.setXml(null);
        mpg.setTemplate(templateConfig);


        // 5、策略配置
        StrategyConfig strategy = new StrategyConfig();
        //**** 添加表名
        strategy.setInclude("tb_cart","tb_company_address","tb_member","tb_order","tb_order_item",
                            "tb_orderpayment","tb_product","tb_product_category","tb_user");
//        strategy.setInclude(SET_INCLUDE);
        strategy.setNaming(NamingStrategy.underline_to_camel);//数据库表映射到实体的命名策略
        strategy.setTablePrefix(pc.getModuleName() + "tb_"); //生成实体时去掉表前缀
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);//数据库表字段映射到实体的命名策略
        strategy.setEntityLombokModel(true); // lombok 模型 @Accessors(chain = true) setter链式操作


        strategy.setEntityTableFieldAnnotationEnable(true);
        strategy.setRestControllerStyle(true); //restful api风格控制器
        strategy.setControllerMappingHyphenStyle(true); //url中驼峰转连字符

        mpg.setStrategy(strategy);
        mpg.setTemplateEngine(new FreemarkerTemplateEngine());

        // 6、执行
        mpg.execute();
    }


}
